package com.misyi.designpattern.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元模式
 *
 * @author licong
 * @date 2021-09-14 下午7:30
 */
public class FlyweightPatternDemo {

    public static void main(String[] args) {
        Flyweight flyweight1 = FlyweightFactory.get("对象1");
        flyweight1.execute();

        Flyweight flyweight2 = FlyweightFactory.get("对象1");
        flyweight2.execute();

        System.out.println(flyweight1 == flyweight2);
    }


    public interface Flyweight {
        void execute();
        void setName(String name);
    }

    public static class ConcreteFlyweight implements Flyweight {

        private String name;

        @Override
        public void execute() {
            System.out.println(name + "执行功能逻辑");

        }

        @Override
        public void setName(String name) {
            this.name = name;
        }
    }

    public static class FlyweightFactory {

        private static Map<String, Flyweight> cachePool = new HashMap<>();

        public static Flyweight get(String name) {
            Flyweight flyweight = cachePool.get(name);
            if (flyweight == null) {
                flyweight = new ConcreteFlyweight();
                flyweight.setName(name);
                cachePool.put(name, flyweight);
            }
            return flyweight;
        }
    }
}
